package com.cxx.purchasecharge.component.controller.usersecurity;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.PCApplicationContext;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.usersecurity.ResourceBean;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.BeanConvertUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.Resource;
import com.cxx.purchasecharge.dal.ResourceDao;

@Controller
@RequestMapping ("/resource")
public class ResourceManager
{
    private static final Logger logger = Logger.getLogger (ResourceManager.class);

    @Autowired
    private ResourceDao resourceDao;
    @Autowired
    private PCApplicationContext pcContext;

    @RequestMapping (value = "/getAllResource", method = RequestMethod.POST)
    public @ResponseBody
    String getResources (DataGridRequestForm dataGridRequestForm)
    {
        List <Resource> resources = (List <Resource>) resourceDao.findAll ();

        JSONArray jsonArray = JSONArray.fromObject (BeanConvertUtils.resourceList2ResourceBeanList (resources));
        return jsonArray.toString ();
    }

    @RequestMapping (value = "/newResource", method = RequestMethod.POST)
    public @ResponseBody
    String addResource (ResourceBean resourceBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                resourceDao.save (BeanConvertUtils.resourceBean2Resource (resourceBean));
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_RESOURCE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_RESOURCE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/updateResource", method = RequestMethod.POST)
    public @ResponseBody
    String updateResource (ResourceBean resourceBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                resourceDao.save (BeanConvertUtils.resourceBean2Resource (resourceBean));
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_RESOURCE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                       ComponentConstants.MSG_RESOURCE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/delResource", method = RequestMethod.POST)
    public @ResponseBody
    String deleteResource (@RequestParam String ids)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            Resource resource;
            List <Resource> resources = new ArrayList <Resource> ();
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String id : idArr)
                {
                    resource = new Resource ();
                    resource.setId (Long.parseLong (id));
                    resources.add (resource);
                }
            }
            else
            {
                resource = new Resource ();
                resource.setId (Long.parseLong (ids));
                resources.add (resource);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                resourceDao.delete (resources);
                pcContext.getSecurityResourceMap(true);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_RESOURCE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                       ComponentConstants.MSG_RESOURCE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/")
    public String redirectToResourceManagement (ModelMap model)
    {
        return "resourceManagement";
    }

    @RequestMapping (value = "/checkExist", method = RequestMethod.POST)
    public @ResponseBody
    String checkExist (@RequestParam String resourceId, @RequestParam String name)
    {
        if (StringUtils.isBlank (resourceId))
        {
            // new
            Resource obj = resourceDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long uid = Long.parseLong (resourceId);
            Resource resource = resourceDao.findByName (name);
            if (null != resource && resource.getId () != uid)
            {
                return "false";
            }
        }

        return "true";
    }

}
